package com.tree.thread.aqs;

import lombok.Data;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName com.tree.thread.aqs
 * Description: <类功能描述>. <br>
 * <p>
 * <使用说明>
 * </p>
 * @Author tree
 * @Date 4/13/24 5:26 PM
 * @Version 1.0
 */
public class AqsConditionTest {

    public static void main(String[] args) {
        Resource res = new Resource();
        Condition newCondition = res.lock.newCondition();
        InputThread inputThread = new InputThread(res,newCondition);
        OutThread outThread = new OutThread(res,newCondition);
        inputThread.start();
        outThread.start();
    }
}


class InputThread extends Thread {
    private Resource res;
    Condition newCondition;
    public InputThread(Resource res, Condition newCondition) {
        this.res = res;
        this.newCondition=newCondition;
    }

    @Override
    public void run() {
        int count = 0;
        while (true) {
            // synchronized (res) {
            res.lock.lock();
            try {
                if (res.flag) {
//                  res.wait();
                    newCondition.await();
                }
                Thread.sleep(1000);
                if (count == 0) {
                    res.userName = "余胜军";
                    res.sex = "男";
                } else {
                    res.userName = "小红";
                    res.sex = "女";
                }
                count = (count + 1) % 2;
                res.flag = true;
//                res.notify();
                newCondition.signal();
            } catch (Exception e) {
                // TODO: handle exception
            }finally {
                res.lock.unlock();
            }
        }

        // }
    }
}

class OutThread extends Thread {
    private Resource res;
    private Condition newCondition;
    public OutThread(Resource res, Condition newCondition) {
        this.res = res;
        this.newCondition=newCondition;
    }

    @Override
    public void run() {
        while (true) {
//            synchronized (res) {
            res.lock.lock();
            try {

                if (!res.flag) {
//                  res.wait();
                    newCondition.await();
                }
                Thread.sleep(1000);
                System.out.println(res.userName + "," + res.sex);
                res.flag = false;
//                res.notify();
                newCondition.signal();
            } catch (Exception e) {
                // TODO: handle exception
            }finally {
                res.lock.unlock();
            }
//            }
        }

    }
}

@Data
class Resource {
    public String userName;
    public String sex;
    public boolean flag = false;
    Lock lock = new ReentrantLock();
}